package oz.mano.online.protoStuf;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class ProtoStufUtil {
	
	public static <T> byte[] seirializer(T o){
		Schema schema = RuntimeSchema.getSchema(o.getClass());
		return ProtostuffIOUtil.toByteArray(o, schema , LinkedBuffer.allocate(256));
	}
	
	public static <T> T deserializer(byte[] bytes,Class<T> clazz){
		T obj = null;
		try {
			obj = clazz.newInstance();
			Schema schema = RuntimeSchema.getSchema(obj.getClass());
			ProtostuffIOUtil.mergeFrom(bytes,obj, schema);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	public static int calcSize(Serializable o){
		int ret = 0;
		class DumbOutPutStream extends OutputStream{
			int count = 0;

			@Override
			public void write(int b) throws IOException {
				//吃产生计数，不做字节处理
				count++;
			}
			
		}
		DumbOutPutStream buf = new DumbOutPutStream();
		ObjectOutputStream os = null;
		try {
			os = new ObjectOutputStream(buf);
			os.writeObject(o);
			ret = buf.count;
		} catch (IOException e) {
			e.printStackTrace();
			ret = -1;
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

}
